<template>
  <section class='f-phone-active'>
    <section class="f-card">
      <p class="f-title">号卡ICCID</p>
      <van-search v-model="iccid" placeholder="请扫描或输入卡板背面的ICCID" clearable left-icon right-icon="scan"
        @click-right-icon="extractCode"></van-search>
      <p v-if="flag" style="font-size: 10px;color: #FF5353;padding-left:15px">未查询到该号卡的信息，请通过下方的供应商的商品来查询号卡激活引导</p>
      <div class="f-submit-btn">
        <van-button style="width: 250px;" round block type="primary" @click="getGuideInfo(1)">查询</van-button>
      </div>
    </section>

    <section class="f-card" style="margin-top: 20px">
      <p class="f-title">号码</p>
      <van-search v-model="phone" placeholder="请输入号码查询" clearable></van-search>
      <p v-if="flag" style="font-size: 10px;color: #FF5353;padding-left:15px">未查询到该号码的信息，请通过下方的供应商的商品来查询号卡激活引导</p>
      <div class="f-submit-btn">
        <van-button style="width: 250px;" round block type="primary" @click="getGuideInfo(3)">查询</van-button>
      </div>
    </section>

    <section v-if="flag" class="f-card f-mt-20 f-pb-30">
      <p class="f-title f-mb-20">供应商商品</p>
      <van-form ref="formRef" input-align="right" error-message-align="right">
        <van-cell-group>
          <van-field v-model="form.shopName" name="shopName" label="供应商" placeholder="请选择要上传的供应商"
            :rules="[{ required: true, message: '请选择要上传的供应商' }]" right-icon="arrow" readonly @click="openPicker('选择供应商')" />
          <van-field v-model="form.goodsName" name="goodsName" label="供应商商品" placeholder="请选择一个供应商商品"
            :rules="[{ required: true, message: '请选择一个供应商商品' }]" right-icon="arrow" readonly @click="openPicker('选择供应商商品')" />
        </van-cell-group>
      </van-form>
    </section>

    <van-popup v-model:show="showPicker" closeable position="bottom" close-icon-position="top-left">
      <p class="f-popup-title">{{pickerTitle}}</p>
      <section v-if="pickerTitle == '选择供应商'">
        <van-picker ref="pickerRef" v-model="selectShopId" :columns="mySupplierList" :columns-field-names="customFieldName"
          :show-toolbar="false" />
        <div class="f-popup-btn">
          <van-button block type="primary" @click="handlePicker()">确定</van-button>
        </div>
      </section>

      <!-- <van-cascader  v-model="cascaderValue" :options="goodsList" :field-names="fieldNames" :show-header="false"
        @finish="handleCascader" /> -->
      <van-picker v-else :columns="goodsList" @cancel="showPicker = false" :columns-field-names="fieldNames"
        @confirm="handleCascader" />

    </van-popup>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import api from '../api'
import { warningDeal } from '@/utils/utils';
import JsBridge from '@/utils/JsBridge.js'

export default {
  name: 'PhoneActive',
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const pickerRef = ref()

    const state = reactive({
      iccid: "",
      phone: null,
      flag: false,
      form: {},

      showPicker: false,
      pickerTitle: '',
      selectShopId: [],
      mySupplierList: [],
      customFieldName: {
        text: 'shopName',
        value: 'shopId',
        children: 'children'
      },

      goodsList: [],
      cascaderValue: '',
      fieldNames: {
        text: 'goodsName',
        value: 'goodsId',
        children: 'goodsInfoList',
      }
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '号卡激活引导',
        show: true,
        left: true,
        leftType: 'back',
        right: false,
        rightText: '',
      });

      getSupplierList()
    })

    const getSupplierList = () => {
      api.mySupplierList().then(res => {
        state.mySupplierList = res.data
      })
    };

    const openPicker = (name) => {
      if (name == '选择供应商') {
        state.pickerTitle = name
        state.showPicker = true
      } else if (name == '选择供应商商品') {
        if (!state.form.shopId) {
          warningDeal('请先选择供应商！')
        } else {
          let json = {
            shopId: state.form.shopId
          }
          api.goodsByOperator(json).then(res => {
            // res.data.forEach((item, index) => {
            //   item.goodsId = index + 1
            //   item.goodsName = item.operator
            // })
            state.goodsList = setGoodsList(res.data)
            console.log(state.goodsList)
            state.pickerTitle = name
            state.showPicker = true
          })

        }
      }
    }

    function setGoodsList(list) {
      const myArr = []
      list && list.map(item => {
        if (!item || !item.goodsInfoList) return
        const myC = [...item.goodsInfoList]
        myC && myC.map(items => {
          items.children = null
        })
        myArr.push(...myC)
      })
      return myArr
    }

    const handlePicker = (e) => {
      let data = pickerRef.value.confirm().selectedOptions[0]
      state.form.shopName = data.shopName
      state.form.shopId = data.shopId
      state.showPicker = false
    }

    const handleCascader = (e) => {
      state.goodsForm = e.selectedOptions[0]
      state.form.goodsName = state.goodsForm.goodsName
      state.form.goodsId = state.goodsForm.goodsId
      state.form.productId = state.goodsForm.productId
      state.showPicker = false
      getGuideInfo(2)
    }

    const extractCode = () => {
      JsBridge.callHandler('qrCode', null, (res) => {
        let isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        if (isiOS) {
          state.iccid = JSON.parse(res).result
        } else {
          state.iccid = res
        }

        console.log('qrCode 响应值 ： ', res);
        setTimeout(() => {
          getGuideInfo(1)
        }, 100)
      })
    }

    const getGuideInfo = (type) => {
      if (type == 1) {
        let json = {
          "goodsId": '',
          "iccid": state.iccid
        }
        api.guideInfo(json).then(res => {
          router.push({
            path: '/index/phoneActive/detail',
            query: {
              iccid: state.iccid
            }
          })
        }).catch(err => {
          state.flag = true
        })
      } else if (type == 3) {
        let json = {
          "phone": state.phone
        }
        api.guideInfo(json).then(res => {
          router.push({
            path: '/index/phoneActive/detail',
            query: {
              phone: state.phone
            }
          })
        }).catch(err => {
          state.flag = true
        })
      } else {
        let json = {
          "goodsId": state.goodsForm.goodsId,
          "iccid": ""
        }
        api.guideInfo(json).then(res => {
          router.push({
            path: '/index/phoneActive/detail',
            query: {
              goodsId: state.goodsForm.goodsId
            }
          })
        })
      }
    }

    const addCacheRoute = () => {
      store.commit("addCacheRoute", 'PhoneActive');
    }

    return {
      ...toRefs(state),
      pickerRef,
      openPicker,
      handlePicker,
      handleCascader,
      extractCode,
      handleCascader,
      getGuideInfo
    }
  }
}
</script>
<style lang='scss' scoped>
.f-phone-active {
  padding: 15px 10px;
  .f-card {
    width: 354px;
    background: #ffffff;
    border-radius: 10px;
    .f-title {
      font-size: 14px;
      font-weight: 500;
      padding-top: 23px;
      padding-left: 15px;
    }
    .f-submit-btn {
      padding: 25px 0;
      display: flex;
      justify-content: center;
    }
  }
}
</style>